﻿#region Using directives

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using ApplicationLibrary.CounterManager;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.Preferences;
using ApplicationLibrary.SqlConnector;
using System.ComponentModel;

#endregion

namespace ApplicationLibrary.DBManager
{
    public partial class DocumentForm : WeifenLuo.WinFormsUI.Docking.DockContent, iScrounger, IDisposable
    {
        #region Private

        protected string ConnectionString { get; private set; }

        protected Control keyControl = null;
        protected DBManager dbManager = null;
        internal ControlBinder controlBinder;
        internal ControlFinder controlFinder = null;
        private List<Scrounger> scroungerList = null;
        private List<MessageData> messageList = null;

        #endregion

        #region Properties

        public List<Scrounger> ScroungerList { get { return scroungerList; } }

        public string formName { get; private set; }

        public ProviderType providerType { get; private set; }

        public List<MessageData> ErrorMessageList { get { return messageList; } }

        public enum NullValue { SetNull, NotSet }

        public bool IsNew { get; private set; }

        public Control KeyControl { get { return keyControl; } }

        public DBMode DocumentMode { get { return (dbManager != null) ? dbManager.Status : DBMode.Browse; } }

        public bool SilentMode
        {
            set
            {
                if (dbManager != null)
                    dbManager.SilentMode = value;
            }
            get
            {
                return (dbManager != null)
                    ? dbManager.SilentMode
                    : false;
            }
        }

        #endregion

        #region Events & Delegate

        public delegate void PostFormLoadEventHandler(object sender, DBManager dbManager);

        public event PostFormLoadEventHandler PostLoaded;

        public delegate bool ToolbarButtonEventHandler(ToolStripButton sender);

        public delegate bool ToolbarSplitButtonEventHandler(ToolStripSplitButton sender);

        public event ToolbarSplitButtonEventHandler OnEnableToolbarSplitButtons;

        public delegate void OpenFormEventHandler(WeifenLuo.WinFormsUI.Docking.DockContent frm, bool modal);

        public event OpenFormEventHandler OpenForm;

        #endregion

        #region ToolbarEvent

        public enum ToolbarEventKind
        {
            New, Edit, Delete, Save
        }

        public bool AddNew()
        {
            return ToolbarEvent(DocumentForm.ToolbarEventKind.New);
        }

        public bool Edit()
        {
            return ToolbarEvent(DocumentForm.ToolbarEventKind.Edit);
        }

        public bool Save()
        {
            return ToolbarEvent(DocumentForm.ToolbarEventKind.Save);
        }

        public bool Delete()
        {
            return ToolbarEvent(DocumentForm.ToolbarEventKind.Delete);
        }

        #endregion

        public DocumentForm()
        {
            InitializeComponent();
        }

        public DocumentForm(string formname)
        {
            ConnectionString = GlobalInfo.DBaseInfo.dbManager.DB_ConnectionString;
            this.providerType = GlobalInfo.LoginInfo.ProviderType;
            formName = formname;
            controlBinder = new ControlBinder();
            controlFinder = new ControlFinder(this);
            scroungerList = new List<Scrounger>();
            messageList = new List<MessageData>();
            InitializeComponent();
        }

        public T FindControl<T>(string ctrlName)
        {
            return controlFinder.Find<T>(ctrlName);
        }

        private bool DoEnableToolbarButtons(ToolStripButton button)
        {
            bool enable = OnEnableToolbarButtons(button);
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    enable &= scr.OnEnableToolbarButtons(button, dbManager);

            return enable;
        }

        protected virtual bool OnEnableToolbarButtons(ToolStripButton button)
        {
            return true;
        }

        protected virtual void OnCustomizeToolbar(ToolStrip toolstrip)
        {
        }

        public void AddCustomButton(string name, string text, Image img, bool separator)
        {
            if (separator)
                tspdbForm.Items.Add(new System.Windows.Forms.ToolStripSeparator());

            ToolStripButton tbb = new System.Windows.Forms.ToolStripButton();
            tbb.Name = name;
            tbb.Text = text;
            tbb.Image = img;
            tbb.TextImageRelation = TextImageRelation.ImageAboveText;
            tbb.Tag = "Custom";
            tbb.Click += new EventHandler(tbb_Click);
            tspdbForm.Items.Add(tbb);
        }

        private void tbb_Click(object sender, EventArgs e)
        {
            this.Validate();
            OnCustomButtonClick((ToolStripButton)sender);
            ScroungerCustomButtonClick((ToolStripButton)sender);
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!this.DesignMode)
                ThemeManager.SetTheme(this);

            ScroungerInitializeComponent();

            ScroungerLoad();
            OnAttachData();
            ScroungerAttachData();
            OnCustomizeToolbar(tspdbForm);
            ScroungerCustomizeToolbar(tspdbForm);

            ManageCursorButton();
            ManageOperationButton();

            //ManageControls(this.Controls, false);

            OnBindData();
            ScroungerBindData();

            if (controlBinder != null)
                controlBinder.Enable(false);

            OnAddSplitMenuButton();
            ScroungerAddSplitMenuButton();

            if (PostLoaded != null)
            {
                PostLoaded(this, dbManager);
                ManageCursorButton();
                ManageOperationButton();
            }
            base.OnLoad(e);
        }

        private void formDB_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Escape)
                e.Handled = true;
        }

        private void formDB_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyData)
            {
                case Keys.F4:
                    if (tbnNew.Enabled)
                        OnNewEvent();
                    break;

                case Keys.F3:
                    if (tbnEdit.Enabled)
                        OnEditEvent();
                    break;

                case Keys.F5:
                    if (tbnDelete.Enabled)
                        OnDeleteEvent();
                    break;

                case Keys.F8:
                    if (tbnFind.Enabled)
                        OnFindEvent();
                    break;

                case Keys.F9:
                    if (tbnSearch.Enabled)
                        OnSearchEvent();
                    break;

                case Keys.F10:
                    if (tbnSave.Enabled)
                        OnSaveEvent();
                    break;

                case Keys.Escape:
                    if (tbnUndo.Enabled)
                        OnUndoEvent();
                    break;
            }
        }

        private void formDB_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = !(OnBeforeClosing() && ScroungerOnBeforeClosing());
            if (dbManager != null && !e.Cancel)
                dbManager.Dispose();
        }

        public bool ButtonNewVisible { set { tbnNew.Visible = value; } }

        public bool ButtonDeleteVisible { set { tbnDelete.Visible = value; } }

        public bool ButtonSearchVisible { set { tbnSearch.Visible = value; tss1.Visible = value; } }

        public Binding BindControl(Control control, iColumn column, NullValue nullValue)
        {
            return BindControl(control, column, "Text", nullValue);
        }

        public Binding BindControl(Control control, iColumn column)
        {
            return BindControl(control, column, "Text", NullValue.SetNull);
        }

        public Binding BindControl(Control control, iColumn column, string property)
        {
            return BindControl(control, column, property, NullValue.SetNull);
        }

        public Binding BindControl(Control control, iColumn column, string property, NullValue nullValue)
        {
            return BindControl(control, column, property, nullValue, Findable.NO);
        }

        public Binding BindControl(Control control, iColumn column, NullValue nullValue, Findable findable)
        {
            return BindControl(control, column, "Text", nullValue, findable);
        }

        public Binding BindControl(Control control, iColumn column, Findable findable)
        {
            return BindControl(control, column, "Text", NullValue.SetNull, findable);
        }

        public Binding BindControl(Control control, iColumn column, string property, Findable findable)
        {
            return BindControl(control, column, property, NullValue.SetNull, findable);
        }

        public Binding BindControl(Control control, iColumn column, string property, NullValue nullValue, Findable findable)
        {
            if ((control.GetType() == typeof(TextBox) || control.GetType().BaseType == typeof(TextBox)) && column.Len > 0)
                ((TextBox)control).MaxLength = column.Len;

            controlBinder.Bind(control, column, property, findable);
            if (dbManager.GetDataColumn(column).DefaultValue is System.DBNull && nullValue == NullValue.SetNull)
                dbManager.GetDataColumn(column).DefaultValue = column.DefaultValue;
            return control.DataBindings.Add(property, dbManager.MasterBinding, column.Name);
        }

        public void BindCounter(ICounterManager bindable)
        {
            Debug.Assert(dbManager != null);
            if (dbManager != null)
                dbManager.BindCounter(ref bindable);      
        }

        public void BindCounter<T>(ref ICounterManager bindable)
        {
            Debug.Assert(dbManager != null);
            if (dbManager != null)
                dbManager.BindCounter(ref bindable);
        }

        //public void BindCounter(ref CounterControl fiscalnocontrol)
        //{
        //    Debug.Assert(dbManager != null);
        //    if (dbManager != null)
        //        dbManager.BindCounter(ref fiscalnocontrol);
        //}

        public Binding BindObject(IBindableComponent bindableObj, iColumn column)
        {
            return BindObject(bindableObj, column, NullValue.SetNull);
        }

        public Binding BindObject(IBindableComponent bindableObj, iColumn column, NullValue nullValue)
        {
            if (dbManager.GetDataColumn(column).DefaultValue is System.DBNull && nullValue == NullValue.SetNull)
                dbManager.GetDataColumn(column).DefaultValue = column.DefaultValue;
            return bindableObj.DataBindings.Add("Value", dbManager.MasterBinding, column.Name);
        }

        public Binding BindLocal(Control control, string property, string datamember)
        {
            controlBinder.Bind(control);
            return control.DataBindings.Add(property, this, datamember);
        }

        public void FindableControl(Control control)
        {
            controlBinder.SetFindable(control, Findable.YES);
        }

        public void FindableControl(Control control, Findable findable)
        {
            controlBinder.SetFindable(control, findable);
        }

        /// <summary>
        /// Only For Enable/Disable Controls
        /// </summary>
        public Binding BindControl(Component control)
        {
            controlBinder.Bind(control);
            if (control.GetType() == typeof(ExtendedDataGridView))
            {
                ((ExtendedDataGridView)control).DocumentForm = this;
                ((ExtendedDataGridView)control).LoadSetting();
            }

            return null;
        }

        public void ShowDialog(bool visible)
        {
            if (!visible)
                this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = visible;
            this.Visible = visible;
            base.Show();
            Application.DoEvents();
        }

        public void BindColumn(DataGridViewColumn gridcol, iColumn column)
        {
            gridcol.Name = column.Name;
            gridcol.DataPropertyName = column.Name;
            gridcol.Tag = column.DefaultValue;
            if (gridcol.CellType == typeof(DataGridViewTextBoxCell) && column.Len > 0)
                ((DataGridViewTextBoxColumn)gridcol).MaxInputLength = column.Len;

            if (dbManager.GetDataColumn(column) != null && dbManager.GetDataColumn(column).DefaultValue is System.DBNull)
                dbManager.GetDataColumn(column).DefaultValue = column.DefaultValue;
        }

        private string PrepareFindQuery()
        {
            return controlBinder.GetFindableString();
        }

        #region Virtual Function

        protected virtual void OnAttachData()
        {
        }

        protected virtual void OnBindData()
        {
        }

        protected virtual void OnExtraBind()
        {
        }

        protected virtual void OnDisableControlsForNew()
        {
        }

        protected virtual void OnDisableControlsForEdit()
        {
        }

        protected virtual void OnValidateControl()
        {
        }

        protected virtual void OnCustomButtonClick(ToolStripButton button)
        {
        }

        protected virtual IRadarParameters GetKeyFromDocument()
        {
            return null;
        }

        protected virtual void OnAddPreferenceButton(PreferenceForm prefForm)
        {
        }

        public virtual bool OnDuringSave()
        {
            return true;
        }

        public virtual bool OnDuringDelete()
        {
            return true;
        }

        #endregion

        #region Scrounger Method

        protected virtual void ScroungerInitializeComponent()
        {
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    scr.InitializerComponent();
        }

        protected virtual void ScroungerLoad()
        {
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    scr.OnLoad();
        }

        protected virtual void ScroungerAttachData()
        {
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    scr.OnAttachData(dbManager);
        }

        protected virtual void ScroungerCustomizeToolbar(ToolStrip toolstrip)
        {
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    scr.OnCustomizeToolbar(toolstrip);
        }

        protected virtual void ScroungerBindData()
        {
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    scr.OnBindData();
        }

        protected virtual void ScroungerPrepareAuxData()
        {
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    scr.OnPrepareAuxData();
        }

        protected virtual void ScroungerValidateControl()
        {
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    scr.OnValidateControl();
        }

        protected virtual void ScroungerAddSplitMenuButton()
        {
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    scr.OnAddSplitMenuButton();
        }

        protected virtual void ScroungerDisableControlsForNew()
        {
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    scr.OnDisableControlsForNew();
        }

        protected virtual void ScroungerAddPreferenceButton(PreferenceForm prefForm)
        {
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    scr.OnAddPreferenceButton(prefForm);
        }

        protected virtual void ScroungerDisableControlsForEdit()
        {
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    scr.OnDisableControlsForEdit();
        }

        protected virtual void ScroungerCustomButtonClick(ToolStripButton button)
        {
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    scr.OnCustomButtonClick(button);
        }

        protected virtual void ScroungerPrintDocument(PrintInfo sender, printerForm pf)
        {
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    scr.OnPrintDocument(sender, pf);
        }

        protected virtual bool ScroungerOnBeforeAddNew()
        {
            bool bOK = true;
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    bOK &= scr.OnBeforeAddNew();

            return bOK;
        }

        protected virtual bool ScroungerOnBeforeUndo()
        {
            bool bOK = true;
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    bOK &= scr.OnBeforeUndo();

            return bOK;
        }

        protected virtual bool ScroungerOnBeforeSave()
        {
            bool bOK = true;
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    bOK &= scr.OnBeforeSave();

            return bOK;
        }

        protected virtual bool ScroungerOnSaveButton()
        {
            bool bOK = true;
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    bOK &= scr.OnSaveButton();

            return bOK;
        }

        protected virtual bool ScroungerOnDeleteButton()
        {
            bool bOK = true;
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    bOK &= scr.OnDeleteButton();

            return bOK;
        }

        

        protected virtual bool ScroungerOnAfterSave()
        {
            bool bOK = true;
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    bOK &= scr.OnAfterSave();

            return bOK;
        }

        protected virtual bool ScroungerOnAfterDelete()
        {
            bool bOK = true;
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    bOK &= scr.OnAfterDelete();

            return bOK;
        }

        protected virtual bool ScroungerOnBeforeDelete()
        {
            bool bOK = true;
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    bOK &= scr.OnBeforeDelete();

            return bOK;
        }

        protected virtual bool ScroungerOnBeforeClosing()
        {
            bool bOK = true;
            if (scroungerList != null)
                foreach (Scrounger scr in scroungerList)
                    bOK &= scr.OnBeforeClosing();

            return bOK;
        }

        #endregion

        #region virtual override function

        protected virtual bool OnNewButton()
        {
            if (OnBeforeAddNew() && ScroungerOnBeforeAddNew())
            {
                IsNew = true;
                bool oK = dbManager.AddNew();
                if (oK)
                {
                    OnPrepareAuxData();
                    ScroungerPrepareAuxData();
                }

                return oK;
            }

            return false;
        }

        protected virtual void OnEditButton()
        {
            IsNew = false;
            dbManager.Edit();
            OnPrepareAuxData();
            ScroungerPrepareAuxData();
        }

        protected virtual bool OnSaveButton()
        {
            //IsNew = false;
            return dbManager.Save();
        }

        protected virtual bool OnDeleteButton()
        {
            if (OnBeforeDelete() && ScroungerOnBeforeDelete())
            {
                IsNew = false;
                return dbManager.Delete();
            }

            return false;
        }

        protected virtual bool OnUndoButton()
        {
            if (OnBeforeUndo() && ScroungerOnBeforeUndo())
            {
                IsNew = false;
                dbManager.Undo();
                OnPrepareAuxData();
                ScroungerPrepareAuxData();
                return true;
            }
            return false;
        }

        protected virtual void OnSearchButton()
        {
            RadarForm myRadar = dbManager.RadarDocument;
            myRadar.FindQuery = string.Empty;

            if (dbManager.Status != DBMode.Find)
                tssStatus.Text = "Search";
            else
                myRadar.FindQuery = PrepareFindQuery();

            myRadar.RadarFormRowSelected += new RadarForm.RadarFormRowSelectedEventHandler(myRadar_RadarFormRowSelected);
            myRadar.ShowDialog();
            myRadar.RadarFormRowSelected -= new RadarForm.RadarFormRowSelectedEventHandler(myRadar_RadarFormRowSelected);
        }

        protected virtual void OnFindButton()
        {
            tssStatus.Text = "Find";
            dbManager.Find();
            ManageToolbarEvents();
        }

        private void myRadar_RadarFormRowSelected(object sender, RadarFormRowSelectedArgs pe)
        {
            FindRecord(pe.parameters);
            if (dbManager.Status == DBMode.Find)
                OnUndoEvent();
        }

        public bool FindRecord(IRadarParameters key)
        {
            bool Found = dbManager.FindRecord(key);
            OnPrepareAuxData();
            ScroungerPrepareAuxData();
            ManageToolbarEvents();

            return Found;
        }

        protected virtual bool OnBeforeClosing()
        {
            if (dbManager != null && dbManager.Status == DBMode.Edit)
            {
                if (MessageBox.Show
                    (
                        Properties.Resources.Exit_Close,
                        Properties.Resources.Warning,
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question
                    ) == DialogResult.Yes)
                {
                    dbManager.Undo();
                    return true;
                }
                else return false;
            }
            else return true;
        }

        protected virtual void OnPrepareAuxData()
        {
        }

        protected virtual bool OnBeforeAddNew()
        {
            return true;
        }

        protected virtual bool OnAfterAddNew()
        {
            return true;
        }

        protected virtual void FocusOnNew()
        {
        }

        protected virtual bool OnBeforeSave()
        {
            return true;
        }

        protected virtual bool OnAfterSave()
        {
            return true;
        }

        protected virtual bool OnBeforeDelete()
        {
            return dbManager != null && dbManager.SilentMode
                    ? true
                    : MessageBox.Show(
                                    Properties.Resources.Msg_Delete,
                                    Properties.Resources.Warning,
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes;
        }

        protected virtual bool OnAfterDelete()
        {
            return true;
        }

        protected virtual bool OnPrintDocument(PrintInfo sender, printerForm pf)
        {
            return true;
        }

        protected virtual bool OnBeforeUndo()
        {
            if (dbManager.isChanged)
                return MessageBox.Show
                    (
                    Properties.Resources.Exit_Undo,
                    Properties.Resources.Warning,
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question
                    ) == DialogResult.Yes;
            else return true;
        }

        #endregion

        #region Move between Records & Update

        private void tbsMove_Click(object sender, ToolBarButtonClickEventArgs e)
        {
            if (dbManager == null) return;

            ToolBarButton btn = e.Button;

            ManageToolbarEvents();
        }

        public bool ToolbarEvent(ToolbarEventKind eventKind)
        {
            bool isOK = true;
            switch (eventKind)
            {
                case ToolbarEventKind.New:
                    OnNewEvent();
                    break;

                case ToolbarEventKind.Edit:
                    isOK = OnEditEvent();
                    break;

                case ToolbarEventKind.Delete:
                    OnDeleteEvent();
                    break;

                case ToolbarEventKind.Save:
                    OnSaveEvent();
                    break;
            }
            return isOK;
        }

        private void OnNewEvent()
        {
            if (OnNewButton())
            {
                IsNew = true;
                OnAfterAddNew();
            }
            ManageToolbarEvents();
            FocusOnNew();
        }

        private bool OnEditEvent()
        {
            IsNew = false;
            if (DocumentMode == DBMode.Find)
            {
                dbManager.LastKey = GetKeyFromDocument();
            }
            if (!dbManager.isLocked)
                OnEditButton();
            else
                return false;

            ManageToolbarEvents();
            return true;
        }

        private void OnSaveEvent()
        {
            if (!this.Validate())
                return;

            OnValidateControl();
            ScroungerValidateControl();

            //dbManager.ValidateControl();
            if (!OnBeforeSave() || !ScroungerOnBeforeSave())
                return;
            OnValidateControl();
            ScroungerValidateControl();

            dbManager.StartTransaction();

            dbManager.ValidateControl();
            if (!ScroungerOnSaveButton() || !OnDuringSave() || !OnSaveButton())
            {
                dbManager.Rollback();
                return;
            }
            dbManager.Commit();
            dbManager.UnlockRecordAndFind();

            OnAfterSave();
            ScroungerOnAfterSave();
            dbManager.Refresh();

            OnPrepareAuxData();
            ScroungerPrepareAuxData();

            ManageToolbarEvents();
            IsNew = false;
            if (this.Modal)
                this.Close();
        }

        private void OnDeleteEvent()
        {
            dbManager.StartTransaction();
            if (!ScroungerOnDeleteButton() || !OnDuringSave() || !OnDeleteButton())
            {
                dbManager.Rollback();
                return;
            }
            dbManager.Commit();
            OnAfterDelete();
            ScroungerOnAfterDelete();
            ManageToolbarEvents();
        }

        private void OnUndoEvent()
        {
            OnValidateControl();

            //dbManager.ValidateControl();
            if (!OnUndoButton()) return;
            IsNew = false;
            ManageToolbarEvents();
            if (this.Modal)
                this.Close();
        }

        private void OnFindEvent()
        {
            OnFindButton();
        }

        private void OnSearchEvent()
        {
            OnSearchButton();

            //ManageToolbarEvents();
        }

        private void OnPreviewEvent(PrintInfo sender)
        {
            printerForm pf = new printerForm(formName, printerForm.PrintMode.Preview, sender.PrintType);
            if (OnPrintDocument(sender, pf))
                OpenForm(pf, GlobalInfo.globalPref.ModalWindow);
        }

        public void OnPrintEvent(PrintInfo sender)
        {
            printerForm pf = new printerForm(formName, printerForm.PrintMode.Print, sender.PrintType);
            OnPrintDocument(sender, pf);
        }

        private void OnPreferenceEvent()
        {
            Preferences.PreferenceForm pf = new Preferences.PreferenceForm();
            OnAddPreferenceButton(pf);
            ScroungerAddPreferenceButton(pf);
            OpenForm(pf, true);
        }

        public void OpenNewForm(WeifenLuo.WinFormsUI.Docking.DockContent df, bool modal)
        {
            if (OpenForm != null)
                OpenForm(df, modal);
        }

        private void ManageToolbarEvents()
        {
            ManageOperationButton();
            ManageCursorButton();
            if (controlBinder != null)
            {
                controlBinder.Enable(dbManager.Status == DBMode.Edit);
                controlBinder.SetFindable(dbManager.Status == DBMode.Find);
            }

            if (dbManager.Status == DBMode.Edit)
            {
                if (IsNew)
                {
                    OnDisableControlsForNew();
                    ScroungerDisableControlsForNew();
                    tssStatus.Text = Properties.Resources.Doc_New;
                }
                else
                {
                    OnDisableControlsForEdit();
                    ScroungerDisableControlsForEdit();
                    tssStatus.Text = Properties.Resources.Doc_Edit;
                }

                if (controlBinder != null)
                    controlBinder.SetFocus();
            }
            else
                tssStatus.Text = Properties.Resources.Doc_Ready;
        }

        private void tbnNew_Click(object sender, EventArgs e)
        {
            OnNewEvent();
        }

        private void tbnEdit_Click(object sender, EventArgs e)
        {
            OnEditEvent();
        }

        private void tbnSave_Click(object sender, EventArgs e)
        {
            OnSaveEvent();
        }

        private void tbnDelete_Click(object sender, EventArgs e)
        {
            OnDeleteEvent();
        }

        private void tbnUndo_Click(object sender, EventArgs e)
        {
            OnUndoEvent();
        }

        private void tbnSearch_Click(object sender, EventArgs e)
        {
            OnSearchEvent();
        }

        private void tbnFind_Click(object sender, EventArgs e)
        {
            OnFindEvent();
        }

        private void tbnFirst_Click(object sender, EventArgs e)
        {
            dbManager.MoveFirst();
            ManageToolbarEvents();
        }

        private void tbnPrev_Click(object sender, EventArgs e)
        {
            dbManager.MovePrevious();
            ManageToolbarEvents();
        }

        private void tbnNext_Click(object sender, EventArgs e)
        {
            dbManager.MoveNext();
            ManageToolbarEvents();
        }

        private void tbnLast_Click(object sender, EventArgs e)
        {
            dbManager.MoveLast();
            ManageToolbarEvents();
        }

        private void tbnMainData_Click(object sender, EventArgs e)
        {
        }

        private void tbnPrint_ButtonClick(object sender, EventArgs e)
        {
            OnPrintEvent(tbnPrint.Tag != null ? (PrintInfo)tbnPrint.Tag : null);
        }

        private void tbnPreview_ButtonClick(object sender, EventArgs e)
        {
            OnPreviewEvent(tbnPreview.Tag != null ? (PrintInfo)tbnPreview.Tag : null);
        }

        private void tbnPref_Click(object sender, EventArgs e)
        {
            OnPreferenceEvent();
        }

        #endregion

        #region Enable Disable Controls

        protected virtual void ManageControls(System.Windows.Forms.Control.ControlCollection controls, bool isNew)
        {
            if (dbManager == null) return;

            bool enabled = dbManager.Status == DBMode.Edit;

            foreach (Control ctrl in controls)
            {
                Debug.WriteLine(string.Format("valido {0}", ctrl.GetType().ToString()));
                if (ctrl.Controls.Count != 0 && ctrl.GetType().BaseType != typeof(ExtendedDataGridView))
                    ManageControls(ctrl.Controls, isNew);

                if (
                    ctrl.GetType() == typeof(DBCheckBox) ||
                    ctrl.GetType() == typeof(RadioButton) ||
                    ctrl.GetType() == typeof(Button) ||
                    ctrl.GetType() == typeof(ComboBox) ||
                    ctrl.GetType() == typeof(DateTimePicker) ||
                    ctrl.GetType() == typeof(RadarTextBox) ||
                    ctrl.GetType() == typeof(TextBox) ||
                    ctrl.GetType() == typeof(TextBox) ||
                    ctrl.GetType() == typeof(DataGridView) ||
                    ctrl.GetType() == typeof(TabPage) ||
                    ctrl.GetType() == typeof(MaskedTextBox) ||
                    ctrl.GetType() == typeof(NumericTextBox) ||
                    ctrl.GetType() == typeof(NumericTextBox1) ||
                    ctrl.GetType() == typeof(DataGridTextBoxColumn))
                    ctrl.Enabled = enabled;

                if (ctrl.GetType().BaseType == typeof(AFSMaskedTextBox) ||
                            ctrl.GetType() == typeof(AFSMaskedTextBox))
                    ((AFSMaskedTextBox)ctrl).ReadOnly = !enabled;
                else
                    if (ctrl.GetType().BaseType == typeof(NumericTextBox1) ||
                        ctrl.GetType() == typeof(NumericTextBox1))
                        ((NumericTextBox1)ctrl).ReadOnly = !enabled;
                    else
                        if (ctrl.GetType().BaseType == typeof(NumericTextBox) ||
                        ctrl.GetType() == typeof(NumericTextBox))
                            ((NumericTextBox)ctrl).ReadOnly = !enabled;
                        else
                            if (ctrl.GetType().BaseType == typeof(DateTextBox) ||
                            ctrl.GetType() == typeof(DateTextBox))
                                ((DateTextBox)ctrl).ReadOnly = !enabled;
                            else
                                if (ctrl.GetType().BaseType == typeof(TextBox) ||
                                ctrl.GetType() == typeof(TextBox))
                                    ((TextBox)ctrl).ReadOnly = !enabled;
                                else
                                    if (ctrl.GetType().BaseType == typeof(AFSMaskedTextBox) ||
                                    ctrl.GetType() == typeof(AFSMaskedTextBox))
                                        ((AFSMaskedTextBox)ctrl).ReadOnly = !enabled;
                                    else
                                        if (ctrl.GetType().BaseType == typeof(TextBox) ||
                                        ctrl.GetType() == typeof(TextBox))
                                            ((TextBox)ctrl).ReadOnly = !enabled;
                                        else
                                            if (ctrl.GetType().BaseType == typeof(DataGridTextBox) ||
                                            ctrl.GetType() == typeof(DataGridTextBox))
                                                ((DataGridTextBox)ctrl).ReadOnly = !enabled;
                                            else
                                                if (ctrl.GetType().BaseType == typeof(DataGrid) ||
                                                ctrl.GetType() == typeof(DataGrid))
                                                    ((DataGrid)ctrl).ReadOnly = !enabled;
                                                else
                                                    if (ctrl.GetType().BaseType == typeof(LookUpCombo) ||
                                                ctrl.GetType() == typeof(LookUpCombo))
                                                        ((LookUpCombo)ctrl).Enabled = enabled;
                                                    else
                                                        if (ctrl.GetType().BaseType == typeof(ExtendedDataGridView) ||
                                                        ctrl.GetType() == typeof(ExtendedDataGridView))
                                                            ((ExtendedDataGridView)ctrl).ReadOnly = !enabled;
                                                        else
                                                            Debug.WriteLine(ctrl.GetType().ToString());
            }
        }

        #endregion

        #region Enable Disable OperationButton

        public void ManageOperationButton()
        {
            try
            {
                if (dbManager != null)
                {
                    bool enableResult = true;

                    enableResult = DoEnableToolbarButtons(tbnNew);
                    tbnNew.Enabled = dbManager.Status == DBMode.Browse && enableResult;

                    enableResult = DoEnableToolbarButtons(tbnEdit);
                    tbnEdit.Enabled = (dbManager.Count > 0 && dbManager.Status == DBMode.Browse && enableResult) || dbManager.Status == DBMode.Find;

                    enableResult = DoEnableToolbarButtons(tbnDelete);
                    tbnDelete.Enabled = dbManager.Count > 0 && dbManager.Status == DBMode.Browse && enableResult;

                    enableResult = DoEnableToolbarButtons(tbnUndo);
                    tbnUndo.Enabled = (dbManager.Status == DBMode.Edit && enableResult) || dbManager.Status == DBMode.Find;

                    enableResult = DoEnableToolbarButtons(tbnSave);
                    tbnSave.Enabled = dbManager.Status == DBMode.Edit && enableResult;

                    enableResult = DoEnableToolbarButtons(tbnSearch);
                    tbnSearch.Enabled = (dbManager.Status == DBMode.Browse && enableResult) || dbManager.Status == DBMode.Find;

                    enableResult = DoEnableToolbarButtons(tbnFind);
                    tbnFind.Enabled = dbManager.Status == DBMode.Browse && enableResult;

                    foreach (ToolStripItem tsb in tspdbForm.Items)
                        if (tsb.Tag != null && tsb.Tag.ToString() == "Custom")
                            tsb.Enabled = DoEnableToolbarButtons((ToolStripButton)tsb);

                    if (OnEnableToolbarSplitButtons != null)
                        enableResult = OnEnableToolbarSplitButtons(tbnPreview) && dbManager.Count > 0;
                    else
                        enableResult = false;
                    tbnPreview.Enabled = dbManager.Status == DBMode.Browse && enableResult;
                    tbnPrint.Enabled = dbManager.Status == DBMode.Browse && enableResult;
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        #endregion

        #region Enable Disable CursorButton

        private void ManageCursorButton()
        {
        }

        #endregion

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            //			OnExtraBind();
        }

        #endregion

        private void DocumentForm_FormClosing(object sender, FormClosingEventArgs e)
        {
        }

        #region Print

        protected virtual void OnAddSplitMenuButton()
        {
        }

        protected void AddSplitPreviewButton(string text, string reportName, PrintType printType, Image image)
        {
            if (tbnPreview.Tag == null)
                tbnPreview.Tag = new PrintInfo(reportName, printType);

            ToolStripMenuItem mnuPrev = new ToolStripMenuItem(text);
            mnuPrev.Click += new EventHandler(mnu_PreviewClick);
            mnuPrev.Tag = new PrintInfo(reportName, printType);
            mnuPrev.Image = image;
            tbnPreview.DropDownItems.Add(mnuPrev);
        }

        protected void AddSplitPrintButton(string text, string reportName, PrintType printType, Image image)
        {
            if (tbnPrint.Tag == null)
                tbnPrint.Tag = new PrintInfo(reportName, printType);

            ToolStripMenuItem mnuPrint = new ToolStripMenuItem(text);
            mnuPrint.Click += new EventHandler(mnu_PrintClick);
            mnuPrint.Tag = new PrintInfo(reportName, printType);
            mnuPrint.Image = image;
            tbnPrint.DropDownItems.Add(mnuPrint);
        }

        private void mnu_PreviewClick(object sender, EventArgs e)
        {
            ToolStripMenuItem mnu = (ToolStripMenuItem)sender;
            OnPreviewEvent(mnu.Tag != null ? (PrintInfo)mnu.Tag : null);
        }

        private void mnu_PrintClick(object sender, EventArgs e)
        {
            ToolStripMenuItem mnu = (ToolStripMenuItem)sender;
            OnPrintEvent(mnu.Tag != null ? (PrintInfo)mnu.Tag : null);
        }

        #endregion

        private void tsbExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #region MessageBox Overload

        public DialogResult MyMessageBox(string text)
        {
            if (SilentMode)
            {
                messageList.Add(new MessageData(this.Name, keyControl.Text, text, ""));
                return System.Windows.Forms.DialogResult.OK;
            }
            else
                return MessageBox.Show(text);
        }

        public DialogResult MyMessageBox(string text, string caption)
        {
            if (SilentMode)
            {
                messageList.Add(new MessageData(this.Name, keyControl.Text, text, caption));
                return System.Windows.Forms.DialogResult.OK;
            }
            else
                return MessageBox.Show(text, caption);
        }

        public DialogResult MyMessageBox(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
        {
            if (SilentMode)
            {
                messageList.Add(new MessageData(this.Name, keyControl.Text, text, caption));
                return System.Windows.Forms.DialogResult.OK;
            }
            else
                return MessageBox.Show(owner, text, caption, buttons, icon);
        }

        public DialogResult MyMessageBox(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
        {
            if (SilentMode)
            {
                messageList.Add(new MessageData(this.Name, keyControl.Text, text, caption));
                return System.Windows.Forms.DialogResult.OK;
            }
            else
                return MessageBox.Show(text, caption, buttons, icon);
        }

        #endregion
    }

    internal class RadarDocumentParam : RadarParameters
    {
        public RadarDocumentParam(Table rdrTable, string code)
        {
            Params = new List<object>();
            for (int t = 0; t < rdrTable.SegmentKeyCount; t++)
                Params.Add(rdrTable.GetKeySegment(t).Name);
        }
    }

    internal static class FindableCleaner
    {
        private static void Clean(this TextBox txtbox)
        {
            txtbox.Text = string.Empty;
        }
    }

    public class MessageData
    {
        public string document { get; private set; }

        public string text { get; private set; }

        public string caption { get; private set; }

        public string key { get; private set; }

        public MessageData(string document, string key, string text, string caption)
        {
            this.document = document;
            this.key = key;
            this.text = text;
            this.caption = caption;
        }
    }
}